from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import pre_save
from django.dispatch import receiver
from django.utils.text import slugify
import re

class Document(models.Model):
    """文档模型"""
    title = models.CharField('标题', max_length=200)
    slug = models.SlugField('URL别名', max_length=200, unique=True)
    category = models.ForeignKey('Category', verbose_name='分类',
                                on_delete=models.CASCADE,
                                related_name='documents')
    tags = models.ManyToManyField('Tag', verbose_name='标签',
                                 blank=True,
                                 related_name='documents')
    description = models.TextField('描述', blank=True)
    content = models.TextField('内容')
    author = models.ForeignKey(User, verbose_name='作者',
                              on_delete=models.CASCADE,
                              related_name='documents',
                              null=True, blank=True)
    views = models.PositiveIntegerField('浏览量', default=0)
    is_published = models.BooleanField('是否发布', default=True)
    is_popular = models.BooleanField('是否热门', default=False)
    is_recommended = models.BooleanField('是否推荐', default=False)
    created_at = models.DateTimeField('创建时间', auto_now_add=True)
    updated_at = models.DateTimeField('更新时间', auto_now=True)

    class Meta:
        verbose_name = '文档'
        verbose_name_plural = verbose_name
        ordering = ['-updated_at']

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return f'/document/{self.slug}/'

    def increase_views(self):
        """增加浏览量"""
        self.views += 1
        self.save(update_fields=['views'])

    def extract_tags(self):
        """从文档标题中提取标签"""
        # 1. 分割标题（按空格、中文顿号、斜杠等分隔符）
        separators = r'[,，\s/、]+'
        words = re.split(separators, self.title)
        
        # 2. 过滤并清理标签
        tags = []
        for word in words:
            # 清理标点符号和空白
            word = re.sub(r'[^\w\u4e00-\u9fff]+', '', word).strip().lower()
            
            # 过滤掉太短或太长的词
            if len(word) > 1 and len(word) <= 20:
                tags.append(word)
        
        return tags

@receiver(pre_save, sender=Document)
def generate_document_slug(sender, instance, **kwargs):
    """生成文档的slug"""
    if not instance.slug:
        instance.slug = slugify(instance.title)

@receiver(pre_save, sender=Document)
def auto_generate_tags(sender, instance, **kwargs):
    """自动生成标签"""
    from .tag import Tag  # 避免循环导入
    
    if instance.pk and instance.is_published:  # 只处理已发布的文档
        # 获取现有标签
        existing_tags = set(instance.tags.values_list('name', flat=True))
        
        # 从标题提取新标签
        new_tags = set(instance.extract_tags())
        
        # 对于新增的标签
        for tag_name in new_tags - existing_tags:
            if tag_name:  # 确保标签名不为空
                try:
                    # 尝试获取已存在的标签
                    tag = Tag.objects.get(name=tag_name)
                except Tag.DoesNotExist:
                    # 生成唯一的slug
                    base_slug = slugify(tag_name)
                    slug = base_slug
                    counter = 1
                    while Tag.objects.filter(slug=slug).exists():
                        slug = f"{base_slug}-{counter}"
                        counter += 1
                    
                    # 创建新标签
                    tag = Tag.objects.create(
                        name=tag_name,
                        slug=slug,
                        description=f'包含 {tag_name} 相关的文档'
                    )
                instance.tags.add(tag) 